import { Engine, World, Bodies, Body, IBodyDefinition, Events } from 'matter-js';

export class PhysicsEngine {
  private engine: Engine;
  private bodies: Map<string, Body>;

  constructor() {
    // 创建物理引擎实例
    this.engine = Engine.create({
      gravity: { x: 0, y: 0 }, // 默认无重力
    });

    // 初始化物理对象存储
    this.bodies = new Map();
  }

  // 添加物理对象
  public addBody(id: string, options: IBodyDefinition): Body {
    const body = Bodies.rectangle(
      options.position?.x || 0,
      options.position?.y || 0,
      options.width || 32,
      options.height || 32,
      options
    );
    
    World.add(this.engine.world, [body]);
    this.bodies.set(id, body);
    return body;
  }

  // 移除物理对象
  public removeBody(id: string): void {
    const body = this.bodies.get(id);
    if (body) {
      World.remove(this.engine.world, body);
      this.bodies.delete(id);
    }
  }

  // 更新物理对象位置
  public updateBodyPosition(id: string, x: number, y: number): void {
    const body = this.bodies.get(id);
    if (body) {
      Body.setPosition(body, { x, y });
    }
  }

  // 更新物理对象旋转
  public updateBodyRotation(id: string, angle: number): void {
    const body = this.bodies.get(id);
    if (body) {
      Body.setAngle(body, angle);
    }
  }

  // 应用力
  public applyForce(id: string, force: { x: number; y: number }): void {
    const body = this.bodies.get(id);
    if (body) {
      Body.applyForce(body, body.position, force);
    }
  }

  // 设置物理对象速度
  public setVelocity(id: string, velocity: { x: number; y: number }): void {
    const body = this.bodies.get(id);
    if (body) {
      Body.setVelocity(body, velocity);
    }
  }

  // 获取物理引擎实例
  public getEngine(): Engine {
    return this.engine;
  }

  // 更新物理引擎
  public update(delta: number = 1000 / 60): void {
    Engine.update(this.engine, delta);
  }

  // 清理资源
  public destroy(): void {
    World.clear(this.engine.world, false);
    Engine.clear(this.engine);
  }

  // 添加碰撞检测
  public addCollisionListener(callback: (bodyA: Body, bodyB: Body) => void): void {
    // @ts-ignore - Matter.js类型定义不完整
    Events.on(this.engine, 'collisionStart', (event) => {
      event.pairs.forEach((pair: any) => {
        callback(pair.bodyA, pair.bodyB);
      });
    });
  }

  // 获取物理对象
  public getBody(id: string): Body | undefined {
    return this.bodies.get(id);
  }
}